<template>
  <div class="container">
    <el-row class="section">
      <el-col :span="12" class="section-title">{{
        $t('contents_overview')
      }}</el-col>
      <el-col :span="12" class="section-toolbar">
        <el-button-group>
          <el-button
            :type="time == 'day' ? 'primary' : ''"
            size="small"
            @click="setDateType('day')"
            >{{ $t('day') }}</el-button
          >
          <el-button
            :type="time == 'week' ? 'primary' : ''"
            size="small"
            @click="setDateType('week')"
            >{{ $t('week') }}</el-button
          >
          <el-button
            :type="time == 'month' ? 'primary' : ''"
            size="small"
            @click="setDateType('month')"
            >{{ $t('month') }}</el-button
          >
        </el-button-group>
      </el-col>
    </el-row>
    <el-card shadow="hover" class="section-card">
      <el-row v-if="infoData.readStatistics">
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <i class="el-icon-s-order user" />
          <p>【{{ timeOpt[time] }}】</p>
          <p>{{ infoData.beginDate }} ~ {{ infoData.endDate }}</p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <p>{{ $t('number_of_new_contents') }}</p>
          <p class="number">{{ infoData.readStatistics.newsCollect }}</p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <p>{{ $t('number_of_approved_contents') }}</p>
          <p class="number">{{ infoData.readStatistics.newsApprove }}</p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <p>{{ $t('content_visitors') }}</p>
          <p class="number">{{ infoData.readStatistics.newsUser }}</p>
          <p class="compare">
            <span
              v-if="infoData.readStatistics.newsUserWeekOnWeek"
              :style="{
                color:
                  infoData.readStatistics.newsUserWeekOnWeek < 0
                    ? '#4CAF50'
                    : '#F56C6C'
              }"
              class="key"
            >
              <i
                :class="
                  infoData.readStatistics.newsUserWeekOnWeek < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(infoData.readStatistics.newsUserWeekOnWeek) }} %
            </span>
            <span v-else>--</span>
            {{ comDateOpt[time] }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="10">
          <p>{{ $t('number_of_reading_contents_in_average') }}</p>
          <p class="number">{{ infoData.readStatistics.readPerCapita }}</p>
          <p class="compare">
            <span
              v-if="infoData.readStatistics.readPerCapitaWeekOnWeek"
              :style="{
                color:
                  infoData.readStatistics.readPerCapitaWeekOnWeek < 0
                    ? '#4CAF50'
                    : '#F56C6C'
              }"
              class="key"
            >
              <i
                :class="
                  infoData.readStatistics.readPerCapitaWeekOnWeek < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(infoData.readStatistics.readPerCapitaWeekOnWeek) }} %
            </span>
            <span v-else>--</span> {{ comDateOpt[time] }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="10">
          <p>{{ $t('average_reading_duration_per_capita') }}(s)</p>
          <p class="number">{{ infoData.readStatistics.readTimePerCapita }}</p>
          <p class="compare">
            <span
              v-if="infoData.readStatistics.readTimePerCapitaWeekOnWeek"
              :style="{
                color:
                  infoData.readStatistics.readTimePerCapitaWeekOnWeek < 0
                    ? '#4CAF50'
                    : '#F56C6C'
              }"
              class="key"
            >
              <i
                :class="
                  infoData.readStatistics.readTimePerCapitaWeekOnWeek < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{
                Math.abs(infoData.readStatistics.readTimePerCapitaWeekOnWeek)
              }}
              % </span
            ><span v-else>--</span> {{ comDateOpt[time] }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="10">
          <p>{{ $t('average_reading_duration_per_single_content') }}(s)</p>
          <p class="number">{{ infoData.readStatistics.readTimePerNews }}</p>
          <p class="compare">
            <span
              v-if="infoData.readStatistics.readTimePerNewsWeekOnWeek"
              :style="{
                color:
                  infoData.readStatistics.readTimePerNewsWeekOnWeek < 0
                    ? '#4CAF50'
                    : '#F56C6C'
              }"
              class="key"
            >
              <i
                :class="
                  infoData.readStatistics.readTimePerNewsWeekOnWeek < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(infoData.readStatistics.readTimePerNewsWeekOnWeek) }}
              % </span
            ><span v-else>--</span> {{ comDateOpt[time] }}
          </p>
        </el-col>
      </el-row>
    </el-card>
    <el-row :gutter="10">
      <el-col :lg="12" :sm="24" :md="24" :xl="12">
        <el-card shadow="hover" class="section-card">
          <div slot="header">
            <span class="echart-title"
              >【{{ timeOpt[time] }}】
              {{ $t('content_uv') }}
              ({{ $t('contents') }})
            </span>
            <br />
            <span class="echart-time"
              >{{ infoData.beginDate }} ~ {{ infoData.endDate }}
            </span>
          </div>
          <div id="NewsRead" class="echart-body menu" />
        </el-card>
      </el-col>
      <el-col :lg="12" :sm="24" :md="24" :xl="12">
        <el-card shadow="hover" class="section-card">
          <div slot="header">
            <span class="echart-title"
              >【{{ dateTypeOpt[time] }}】
              {{ $t('content_visitors') }}
              ({{ $t('users') }})
            </span>
            <br />
            <span class="echart-time"
              >{{ infoData.userBeginDate }} ~ {{ infoData.userEndDate }} |
              {{ $t('past') }} {{ dateTypeOpt[time] }}</span
            >
          </div>
          <div id="NewUsersCount" class="echart-body menu" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import echarts from 'echarts';
import { newsDataApi } from '@/api/data-overview.js';
import textFormatting from '@/utils/textFormatting.js';
import '@/assets/css/common/style.scss';

export default {
  data() {
    return {
      time: 'day',
      infoData: {},
      NewsReadEchart: null,
      NewUsersEchart: null,
      comDateOpt: {
        day: this.$t('compared_to_last_week'),
        week: this.$t('compared_to_last_week'),
        month: this.$t('compared_to_last_month')
      },
      timeOpt: {
        day: this.$t('yesterday'),
        week: this.$t('last_week'),
        month: this.$t('last_month')
      },
      dateTypeOpt: {
        day: this.$t('a_7_days'),
        week: this.$t('a_7_weeks'),
        month: this.$t('a_6_months')
      },
      newsTypeOpt: {
        article: this.$t('image_text'),
        gallery: this.$t('photo_album'),
        other: this.$t('others'),
        smallVideo: this.$t('Short_video'),
        video: this.$t('video')
      }
    };
  },

  mounted() {
    this.getInfoData();
    window.addEventListener('resize', () => {
      this.NewsReadEchart.resize();
      this.NewUsersEchart.resize();
    });
  },

  methods: {
    setDateType(type) {
      this.time = type;
      this.getInfoData();
    },

    initNewsReadEchart() {
      const self = this;
      this.NewsReadEchart = echarts.init(document.getElementById('NewsRead'));
      this.NewsReadEchart.showLoading();
      const data = [];
      const legend = [];
      if (this.infoData.newsReadUV.total != 0) {
        const sortedNewsCount = Object.keys(this.infoData.newsReadUV).sort(
          (a, b) => this.infoData.newsReadUV[b] - this.infoData.newsReadUV[a]
        );
        sortedNewsCount.forEach(item => {
          if (item != 'total') {
            legend.push(this.newsTypeOpt[item]);
            data.push({
              value: this.infoData.newsReadUV[item],
              name: this.newsTypeOpt[item]
            });
          }
        });
      }
      this.NewsReadEchart.hideLoading();
      this.NewsReadEchart.setOption({
        color: this.$store.state.app.eChartColor,
        title: {
          zlevel: 0,
          text: [
            this.$t('total_reading_amount'),
            self.infoData.newsReadUV.total
          ].join('\n\n'),
          rich: {
            value: {
              color: '#303133',
              fontSize: 40,
              fontWeight: 'bold',
              lineHeight: 40
            },
            name: {
              color: '#909399',
              lineHeight: 20
            }
          },
          top: 'center',
          left: '35%',
          textAlign: 'center',
          textStyle: {
            rich: {
              value: {
                color: '#303133',
                fontSize: 40,
                fontWeight: 'bold',
                lineHeight: 40
              },
              name: {
                color: '#909399',
                lineHeight: 20
              }
            }
          }
        },
        tooltip: {
          show: true,
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: '80',
          itemGap: 15,
          selectedMode: false, // 取消图例上的点击事件
          formatter(name) {
            let tarValue;
            data.forEach(item => {
              if (item.name == name) {
                tarValue = item.value;
              }
            });

            const p = textFormatting.fomatFloat(
              (tarValue / self.infoData.newsReadUV.total) * 100,
              2
            );
            const arr = [`{a|${name}}`, `{b|${tarValue}}`, `{c|${p}%}`];
            return arr.join(' ');
          },
          textStyle: {
            rich: {
              a: {
                fontSize: 12,
                align: 'left',
                width: 70
              },
              b: {
                fontSize: 12,
                align: 'left',
                width: 70
              }
            }
          },
          data: legend
        },
        series: [
          {
            center: ['35%', '50%'],
            name: this.$t('reading_amount'),
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: false
              }
            },
            data
          }
        ]
      });
    },

    initNewUsersEchart() {
      this.NewUsersEchart = echarts.init(
        document.getElementById('NewUsersCount')
      );
      this.NewUsersEchart.showLoading();
      const date = [];
      const value = [];
      this.infoData.newsUser.forEach(item => {
        date.push(item.date);
        value.push(item.total);
      });
      this.NewUsersEchart.hideLoading();
      this.NewUsersEchart.setOption({
        color: this.$store.state.app.eChartColor,
        xAxis: {
          type: 'category',
          data: date
        },
        yAxis: {
          type: 'value'
        },
        tooltip: {
          trigger: 'axis'
        },
        series: [
          {
            data: value,
            type: 'line'
          }
        ]
      });
    },

    getInfoData() {
      newsDataApi({ time: this.time })
        .then(result => {
          if (result.code == 200) {
            this.infoData = result.data;
            Object.keys(this.infoData.readStatistics).forEach(item => {
              if (
                item != 'newsCollect' &&
                item != 'newsApprove' &&
                item != 'newsUser'
              ) {
                this.infoData.readStatistics[item] = textFormatting.fomatFloat(
                  result.data.readStatistics[item],
                  2
                );
              }
            });
            this.initNewsReadEchart();
            this.initNewUsersEchart();
          } else {
            this.$message.error(result.msg);
          }
        })
        .catch(() => {});
    }
  }
};
</script>
